package com.yuncheng.sms.utils;

import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.utils.SmsUtils;
import com.yuncheng.vo.HttpResult;
import org.gxfda.sms.client.ISmsClientHelper;
import org.gxfda.sms.client.SmsClientHelperImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.PrivateKey;

@Component
public class SmsClient {

    private final Logger LOGGER = LoggerFactory.getLogger(SmsClient.class);
    //移动端端短信验证信息
    public static final String MOBILE_CHECK_MESSAGE = "您正在登录广西药品智慧监管平台，验证码：";
    //系统消息发送部门
    public static final String SYS_DEPT_NAME = "信息与监控中心";
    //系统消息发送人
    public static final String SYS_SENDER = "系统管理员";

    //短信应用id,由局方分配,一般为私钥文件第一个前缀
    @Value("${yjjsms.appId}")
    private String appId;
    //短信服务地址
    @Value("${yjjsms.serviceAddress}")
    private String serviceAddress;
    //短信签名私钥,向局方申请,为x509格式pem文件
    private static PrivateKey privateKey = null;

    @Resource
    private SmsUtils smsUtils;

    /**
     * 初始化短信签名私钥
     *
     * @param keyFilePath 私钥路径
     */
    @Value("${yjjsms.keyFilePath}")
    public void initPrivateKey(String keyFilePath) {
        try {
            privateKey = SmsClientHelperImpl.readPrivateKey(keyFilePath);
        } catch (Exception e) {
            LOGGER.error("短信签名私钥初始化失败: " + e.getMessage(),e);
        }
    }

    /**
     * 短信发送工具
     *
     * @param sendPhone 发送电话,默认一个,多个电话分号间隔,发送电话不能超过100个
     * @param mssageContent 短信内容,utf-8编码
     * @param deptName 发送单位
     * @param sender 发送人
     * @return 发送结果
     */
    public HttpResult<?> sendMessage(String sendPhone, String mssageContent, String deptName, String sender) {
        String result = "";
        try {
            ISmsClientHelper smsClient = SmsClientHelperImpl.getInstance(appId, privateKey, serviceAddress);
//            result = smsClient.httpSendSms(sendPhone, mssageContent, deptName, sender);
//            result = smsClient.httpSendSms(sendPhone, "【"+ BusinessConstant.Dw_NAME +"】" + mssageContent, BusinessConstant.Dw_NAME, sender);
            result = smsUtils.sendSmsZdy(sendPhone, mssageContent);
        } catch (Exception e) {
            LOGGER.error("短信发送失败: " + e.getMessage(),e);
            return HttpResult.error(result);
        }
        if ("00".equals(result) || BusinessConstant.SMS_FLAG.contains(result)) {
            return HttpResult.ok(result);
        } else {
            return HttpResult.error(result);
        }
    }

}
